import Vue from 'vue'
import Router from 'vue-router'

const Login = () =>
    import ("./components/Login")
const Home = () =>
    import ("./components/Home")
const Welcome = () =>
    import ('./components/Welcome')
const Users = () =>
    import ('./components/user/Users')


Vue.use(Router)

const routes = [{
    path: '/',
    redirect: '/login'
}, {
    path: '/login',
    component: Login
}, {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    // 子路由
    children: [{
        path: '/welcome',
        component: Welcome,
    }, {
        path: '/users',
        component: Users,
    }]
}]

const router = new Router({
    routes
})
router.beforeEach((to, from, next) => {
    // to是跳转到哪个页面
    // from是从哪个页面跳转
    // next是放行，next()放行，next('/login')强制跳转
    //    如果是跳转到login的，直接放行
    if (to.path === '/login') {
        return next()
    }
    // 获取token,如果token没值则跳转login,有值则放行
    const tokenStr = window.sessionStorage.getItem('token')
    if (!tokenStr) {
        return next('/login')
    } else {
        next()
    }
})

export default router